package net.cmkj.mine.core.admin.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import net.cmkj.mine.bean.Columns;
import net.cmkj.mine.bean.Modules;
import net.cmkj.mine.common.model.DataGridModel;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.util.CommonUtils;
import net.cmkj.mine.util.DataGridModelUtils;
import net.cmkj.mine.util.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.*;

public class InterfaceService {
	
	private static Logger log = LogManager.getLogger(InterfaceService.class);
	private Modules dao = Modules.dao;
	private Columns cdao = Columns.dao;

	public DataGridModel getAllColumns(int pageNumber, int pageSize, long moduleid, String name, Integer status, String orderbyStr) throws Exception {
		log.info("获取所有表字段信息");
		Page<Columns> pageInfo = cdao.getList(pageNumber, pageSize, moduleid, name, status, orderbyStr);
		DataGridModel result = DataGridModelUtils.toDataGridView(pageInfo);
		return result;
	}

    public DataGridModel getParameterColumns(long moduleid, String name, Integer status, String orderbyStr) throws Exception {
        log.info("获取返回参数字段列表");
        List<Columns> columnsList = cdao.getList(moduleid,name,status,orderbyStr);
        Modules module = dao.findById(moduleid);
        if(module!=null){
            if(CommonUtils.isNotEmpty(module.getBodyColumn())){
                String bodyColumn = module.getBodyColumn();
                String columnIds[] = bodyColumn.split(",");
                for (String columnId : columnIds) {
                    for (Columns column : columnsList) {
                        if (column.getId().longValue()==Long.valueOf(columnId)) {
                            column.setStatus(2);
                        }
                    }
                }
            }
            if(CommonUtils.isNotEmpty(module.getHeaderColumn())){
                String headerColumn = module.getHeaderColumn();
                String columnIds[] = headerColumn.split(",");
                for (String columnId : columnIds) {
                    for (Columns column : columnsList) {
                        if (column.getId().longValue()==Long.valueOf(columnId)) {
                            column.setStatus(2);
                        }
                    }
                }
            }
            if(CommonUtils.isNotEmpty(module.getQueryColumn())){
                String queryColumn = module.getQueryColumn();
                String columnIds[] = queryColumn.split(",");
                for (String columnId : columnIds) {
                    for (Columns column : columnsList) {
                        if (column.getId().longValue()==Long.valueOf(columnId)) {
                            column.setStatus(2);
                        }
                    }
                }
            }
        }
        return DataGridModelUtils.toDataGridView(columnsList);
    }

    public List<Columns> getHeaderSearchList(long moduleid) throws Exception {
        log.info("获取表字段列表");
        return cdao.getList(moduleid);
    }

    public List<String> getHeaderSearchedList(long moduleid) throws Exception {
        log.info("获取已设置查询字段列表");
        List<String> result = new ArrayList<String>();
        Modules module = dao.findById(moduleid);
        String searchids = module.getHeaderColumn();
        if (StrKit.notBlank(searchids)) {
            String[] ids = searchids.split(",");
            for (String id : ids) {
                result.add(id);
            }
        }
        return result;
    }

    public List<Columns> getBodySearchList(long moduleid) throws Exception {
        log.info("获取表字段列表");
        return cdao.getList(moduleid);
    }

    public List<String> getBodySearchedList(long moduleid) throws Exception {
        log.info("获取已设置查询字段列表");
        List<String> result = new ArrayList<String>();
        Modules module = dao.findById(moduleid);
        String searchids = module.getBodyColumn();
        if (StrKit.notBlank(searchids)) {
            String[] ids = searchids.split(",");
            for (String id : ids) {
                result.add(id);
            }
        }
        return result;
    }

    public List<Columns> getQuerySearchList(long moduleid) throws Exception {
        log.info("获取表字段列表");
        return cdao.getList(moduleid);
    }

    public List<String> getQuerySearchedList(long moduleid) throws Exception {
        log.info("获取已设置查询字段列表");
        List<String> result = new ArrayList<String>();
        Modules module = dao.findById(moduleid);
        String searchids = module.getQueryColumn();
        if (StrKit.notBlank(searchids)) {
            String[] ids = searchids.split(",");
            for (String id : ids) {
                result.add(id);
            }
        }
        return result;
    }

    public InvokeResult updateHeader(long moduleid,String ids, int type) throws Exception{
        Modules module = dao.findById(moduleid);
        if(module!=null){
            String headerColumn = module.getHeaderColumn();
            if(type==0){ //添加
                if(headerColumn!=null && headerColumn.length()>0){
                    module.setHeaderColumn(headerColumn+","+ids);
                }else{
                    module.setHeaderColumn(ids);
                }
            }else if(type==1){//删除
                if(headerColumn!=null && headerColumn.length()>0){
                    String newColumn = "";
                    List<String> columnList = getNewColumn(headerColumn, ids);
                    for (String column : columnList) {
                        if(newColumn.length()>0){
                            newColumn+=","+column;
                        }else{
                            newColumn+=column;
                        }
                    }
                    module.setHeaderColumn(newColumn);
                }
            }
            if(module.update()){
                return InvokeResult.success();
            }else {
                return InvokeResult.failure("操作失败！");
            }
        }else{
            return InvokeResult.failure("模块数据有误！");
        }
	}

    public InvokeResult updateBody(long moduleid,String ids, int type) throws Exception{
        Modules module = dao.findById(moduleid);
        if(module!=null){
            String bodyColumn = module.getBodyColumn();
            if(type==0){ //添加
                if(bodyColumn!=null && bodyColumn.length()>0){
                    module.setBodyColumn(bodyColumn+","+ids);
                }else{
                    module.setBodyColumn(ids);
                }
            }else if(type==1){//删除
                if(bodyColumn!=null && bodyColumn.length()>0){
                    String newColumn = "";
                    List<String> columnList = getNewColumn(bodyColumn, ids);
                    for (String column : columnList) {
                        if(newColumn.length()>0){
                            newColumn+=","+column;
                        }else{
                            newColumn+=column;
                        }
                    }
                    module.setBodyColumn(newColumn);
                }
            }
            if(module.update()){
                return InvokeResult.success();
            }else {
                return InvokeResult.failure("操作失败！");
            }
        }else{
            return InvokeResult.failure("模块数据有误！");
        }
    }

    public InvokeResult updateQuery(long moduleid,String ids, int type) throws Exception{
        Modules module = dao.findById(moduleid);
        if(module!=null){
            String queryColumn = module.getQueryColumn();
            if(type==0){ //添加
                if(queryColumn!=null && queryColumn.length()>0){
                    module.setBodyColumn(queryColumn+","+ids);
                }else{
                    module.setBodyColumn(ids);
                }
            }else if(type==1){//删除
                if(queryColumn!=null && queryColumn.length()>0){
                    String newColumn = "";
                    List<String> columnList = getNewColumn(queryColumn, ids);
                    for (String column : columnList) {
                        if(newColumn.length()>0){
                            newColumn+=","+column;
                        }else{
                            newColumn+=column;
                        }
                    }
                    module.setQueryColumn(newColumn);
                }
            }
            if(module.update()){
                return InvokeResult.success();
            }else {
                return InvokeResult.failure("操作失败！");
            }
        }else{
            return InvokeResult.failure("模块数据有误！");
        }
    }

    public List<String> getNewColumn (String oldClumns, String ids) throws Exception {
        String[] columns = oldClumns.split(",");
        String[] allIds = ids.split(",");
        List<String> columnList = new ArrayList<>(columns.length);
        for (String s : columns) {
            columnList.add(s);
        }
        for (int j = 0; j < columnList.size(); j++) {
            String column = columnList.get(j);
            for (int i = 0; i < allIds.length; i++) {
                String columnId = allIds[i];
                if(Long.valueOf(columnId).longValue() == Long.valueOf(column).longValue()){
                    columnList.remove(column);
                    j--;
                }
            }
        }
        return columnList;
    }

    public InvokeResult updateColumnsInterfaceName(Long id, String name) {
        Columns columns = cdao.findById(id);
        if(columns!=null){
            columns.setInterfaceName(name);
            if(columns.update()){
                return InvokeResult.success();
            }else{
                return InvokeResult.failure("操作失败！");
            }
        }else {
            return InvokeResult.failure("模块数据有误！");
        }
    }

    public InvokeResult updateInterface(Long id,String interfaceUrl,String successName,String successCode,String successMsg ,Integer requestType, Integer isToken, String tokenKey, String tokenValue, Integer tokenPosition, Integer isEncrypt, Integer encryptType, Integer encryptColumn) {
        Modules modules = dao.findById(id);
        if(modules!=null){
            modules.setInterfaceUrl(interfaceUrl);
            modules.setSuccessName(successName);
            modules.setSuccessCode(successCode);
            modules.setSuccessMsg(successMsg);
            modules.setRequestType(requestType);
            modules.setIsToken(isToken);
            if(CommonUtils.isNotEmpty(tokenKey)&&CommonUtils.isNotEmpty(tokenValue)){
                modules.setToken(tokenKey+":"+tokenValue);
            }
            modules.setTokenPosition(tokenPosition);
            modules.setIsEncrypt(isEncrypt);
            modules.setEncryptType(encryptType);
            modules.setEncryptColumn(encryptColumn);
            modules.update();
        }else {
            return InvokeResult.failure("模块数据有误！");
        }

        return InvokeResult.success();
    }

    public InvokeResult sendRequest(Modules modules, Map<String, String> header, Map<String, Object> body,Map<String, Object> query,List<String> fileNames) {
        String url = modules.getInterfaceUrl();//url
        Integer requestType = modules.getRequestType(); //请求方式 1=get 2=post
        Integer isToken = modules.getIsToken(); //是否有token  1:是  2：否
        Integer tokenPosition = modules.getTokenPosition(); //token所在参数位置 1=header 2=body
        Integer isEncrypt = modules.getIsEncrypt(); //是否加密  1：是  2：否
        Integer encryptType = modules.getEncryptType(); //加密方式 1=MD5  2=SHA1 3=SHA256
        Integer encryptColumn = modules.getEncryptColumn(); //加密参数 1=header  2=body 3=header和body
        String tokenKey = "";
        String tokenVal = "";
        if(isToken!=null && isToken==1){
            String token = modules.getToken();
            if(CommonUtils.isNotEmpty(token)){
                String[] split = token.split(":");
                if(split.length!=2){
                    return InvokeResult.failure("token数据有误！");
                }else{
                    tokenKey = split[0];
                    tokenVal = split[1];
                }
            }else{
                return InvokeResult.failure("token数据有误！");
            }

            if(tokenPosition!=null && tokenPosition==1){//header
                header.put(tokenKey, tokenVal);
            }else if(tokenPosition!=null && tokenPosition==2){//body
                body.put(tokenKey, tokenVal);
            }else{
                return InvokeResult.failure("token位置参数配置有误！");
            }
        }

        try {
            JSONObject jsonResult = null;
            if(requestType!=null && requestType==1){//get
                jsonResult = JSONObject.parseObject(HttpClient.httpGet(url, mapToString(query), header));
            }else if(requestType!=null && requestType==2){//post
                List<BasicNameValuePair> params = new ArrayList<>();
                if(query.size()>0){
                    for (String o : header.keySet()) {
                        params.add(new BasicNameValuePair(o,header.get(o)));
                    }
                }
                jsonResult = JSONObject.parseObject(HttpClient.httpPost(url,params,JSON.toJSONString(body), header));
            }else{
                return InvokeResult.failure("接口请求方式有误！");
            }
            String successCode = modules.getSuccessCode();
            String successName = modules.getSuccessName();
            String successMsg = modules.getSuccessMsg();
            JSONObject resultCode = jsonResult;
            JSONObject resultMsg = jsonResult;
            if(CommonUtils.isNotEmpty(successCode) && CommonUtils.isNotEmpty(successName)){
                String[] nameSplit = successName.split(",");
                for (int i = 0; i < nameSplit.length; i++) {
                    String s = nameSplit[i];
                    if(i!=nameSplit.length-1){
                        if(resultCode!=null){
                            resultCode = resultCode.getJSONObject(s);
                        }else{
                            return InvokeResult.failure("数据获取失败！");
                        }
                    }else{
                        List<Map<String, Object>> list = new ArrayList<>();
                        String code = resultCode.get(s).toString();
                        if(code.equals(successCode)){
                            if(jsonResult!=null){
                                List<Columns> dataColumn = getInterfaceDataColumn(modules);
                                for (Columns columns : dataColumn) {
                                    Map<String, Object> map = new HashMap<>();
                                    if(jsonResult.getJSONArray("rows").size()>0){
                                        JSONObject resultDate = jsonResult.getJSONArray("rows").getJSONObject(0);
                                        String interfaceName = columns.getInterfaceName();
                                        String[] split = interfaceName.split(",");
                                        for (int j = 0; j < split.length; j++) {
                                            String name = split[i];
                                            if(j==split.length-1){
                                                String val = resultDate.getString(name);
                                                map.put("name", columns.getColumnName());
                                                map.put("value", val);
                                                list.add(map);
                                            }else{
                                                resultDate = resultDate.getJSONObject(name);
                                            }
                                        }
                                    }else{
                                        return InvokeResult.failure("暂无数据！");
                                    }
                                }
                                return InvokeResult.success(list);
                            }else{
                                return InvokeResult.failure("数据获取失败！");
                            }
                        }else{
                            if(CommonUtils.isNotEmpty(successMsg)){
                                String[] msgSplit = successMsg.split(",");
                                for (int j = 0; j < msgSplit.length; j++) {
                                    if(j!=msgSplit.length-1){
                                        if(resultMsg!=null){
                                            resultMsg = resultMsg.getJSONObject(s);
                                        }else{
                                            return InvokeResult.failure("数据获取失败！");
                                        }
                                    }else{
                                        return InvokeResult.failure(resultMsg.get(s).toString());
                                    }
                                }
                            }else{
                                return InvokeResult.failure("数据获取失败！");
                            }
                        }
                    }
                }
            }else{
                return InvokeResult.failure("成功标识配置有误！");
            }
        }catch (Exception e){
            return InvokeResult.failure("接口调用异常！");
        }
        return InvokeResult.success();
    }

    public List<Columns>  getInterfaceDataColumn(Modules modules) throws Exception {
        List<Columns> columnsList = cdao.getList(modules.getId(),null,null,"");
        for (int i = 0; i < columnsList.size(); i++) {
            Columns columns = columnsList.get(i);
            if(!CommonUtils.isNotEmpty(columns.getInterfaceName())){
                columnsList.remove(columns);
                i--;
            }
        }
        String queryColumn = modules.getQueryColumn();
        if(CommonUtils.isNotEmpty(queryColumn)){
            String[] split = queryColumn.split(",");
            for (int i = 0; i < columnsList.size(); i++) {
                Columns columns = columnsList.get(i);
                for (String s : split) {
                    if(columns.getId().longValue()==Long.valueOf(s).longValue()){
                        columnsList.remove(columns);
                        i--;
                    }
                }
            }
        }
        String bodyColumn = modules.getBodyColumn();
        if(CommonUtils.isNotEmpty(bodyColumn)){
            String[] split = bodyColumn.split(",");
            for (int i = 0; i < columnsList.size(); i++) {
                Columns columns = columnsList.get(i);
                for (String s : split) {
                    if(columns.getId().longValue()==Long.valueOf(s).longValue()){
                        columnsList.remove(columns);
                        i--;
                    }
                }
            }
        }
        String headerColumn = modules.getHeaderColumn();
        if(CommonUtils.isNotEmpty(headerColumn)){
            String[] split = headerColumn.split(",");
            for (int i = 0; i < columnsList.size(); i++) {
                Columns columns = columnsList.get(i);
                for (String s : split) {
                    if(columns.getId().longValue()==Long.valueOf(s).longValue()){
                        columnsList.remove(columns);
                        i--;
                    }
                }
            }
        }
        return columnsList;
    }

    public static String mapToString(Map<String, Object> map){
        String[] keyArray = map.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyArray) {
            stringBuilder.append(key).append("=").append(map.get(key)).append("&");
        }
        String s = stringBuilder.toString();
        return s.substring(0, s.length() - 1);
    }

    public static void main(String[] args) {
	    try {
	        Map<String, String> header = new HashMap<>();
            header.put("token", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJpQ1dMYXh0ZFZKYTJLZ05FTnRjeXJZS3EiLCJzdWIiOiJVeGVvOXBxbDFhbzU2ZVY0NndBY2JrQjV3NDBWZ2hhNyIsImlhdCI6MTY1MzU1MDAyM30.vyYCVJk_X_h7WClGt0JhwoyU5S_GyNcvnQQznuP2xkM");
            Map<String, Object> map = new HashMap<>();
            map.put("invoiceNumber", "05362677");
            String s = HttpClient.httpPost("http://financetool.zzcmkj.net/invoice/invoice/invoiceList", JSON.toJSONString(map), header);
            System.err.println(s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            System.err.println(jsonObject.size());
        }catch (Exception e){

        }

    }
}
